package com.gjy.service.k8s.config;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.ConnectionInfo;
import ch.ethz.ssh2.Session;
import com.gjy.service.k8s.property.SSHYaml;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-09-04 10:53:28
 */
//@Configuration
public class SSHConfig {

    private static final Logger log = LoggerFactory.getLogger(SSHConfig.class);

    @Resource
    private SSHYaml sshYaml;

    @Bean(name = "ssh")
    public Session ssh() {
        try {
            Connection connection = new Connection(sshYaml.getIp());
            ConnectionInfo info = connection.connect();
            log.info("ssh info {}", info);

            if (connection.authenticateWithPassword(sshYaml.getUsername(), sshYaml.getPassword())) {
                return connection.openSession();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.info("获取远程连接失败: {}", e.getMessage());
            return null;
        }
    }

}
